//
//  NetWorkUtil.m
//  mytianya
//
//  Created by jiao qiang on 10-6-28.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "NetworkUtil.h"


@implementation NetworkUtil;

@synthesize connection;
@synthesize recvData;
@synthesize loginCookie;
@synthesize beTerminated;

- (id) initWithURL:(NSURL*)url  withOperation:(NSString *)operation withDelegate:(id)sender onComplete:(SEL)callback onError:(SEL)err_callback {
	
	NSLog(@"network begin..........................................##");
	
	self.beTerminated = NO;
	
	parentDelegate = [sender retain];
	onCompleteCallback = callback;
	onErrorCallBack = err_callback;
	
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

	//[request setValue:@"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)" forHTTPHeaderField:@"user-agent"];
	//[request setValue:@"http://khd.3g.tianya.cn" forHTTPHeaderField:@"Referer"];
	//NSLog([Config getLoginCookie]);
	//[request addValue:[Config getLoginCookie] forHTTPHeaderField:@"Cookie"];

	[request setURL:url];
	[request setHTTPMethod:@"GET"];
	[request setTimeoutInterval:30];
	
	//[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
	
	NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	[request release];
	self.connection = conn;
	[conn release];
	
	NSMutableData *data = [[NSMutableData alloc] init];
	self.recvData = data;
	[data release];
	
	return self;
}


- (id) initPostWithURL:(NSURL*)url  body:(NSString*)body withOperation:(NSString *)operation withDelegate:(id)sender onComplete:(SEL)callback onError:(SEL)err_callback {
	parentDelegate = [sender retain];
	onCompleteCallback = callback;
	onErrorCallBack = err_callback;
	
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
	[request setHTTPShouldHandleCookies:YES];

	NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; 
	//[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
	[request setHTTPMethod:@"POST"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
	[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
	
	NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	self.connection = conn;
	[conn release];
	
	NSMutableData *data = [[NSMutableData alloc] init];
	self.recvData = data;
	[data release];

	return self;
}

- (void)terminate {
	if (self.connection != nil) {
		[connection cancel];
		[connection release];
		connection = nil;
		self.beTerminated = YES;
		
		if ([parentDelegate respondsToSelector:onErrorCallBack]) {
			[parentDelegate performSelector:onErrorCallBack withObject:self];
		}
	}
}


#pragma mark NSURLConnection Delegate methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

	NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
	NSDictionary *fields = [HTTPResponse allHeaderFields];
	NSString *cookie = [fields valueForKey:@"Set-Cookie"]; 
	//self.loginCookie = cookie;
	if ([cookie length] > 0) {
		NSHTTPCookie *cook;
		for (cook in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
			NSLog(@"........%@", cook);
			//[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cook];
		}
		
	}
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[recvData appendData:data];
	NSInteger receivedLen = [data length];
	bytesReceived = (bytesReceived + receivedLen);
		
	//if we can not get the expect length, we assume 30000 
	if(expectedBytes == NSURLResponseUnknownLength) {
		expectedBytes = 30000;
	}
	
	//if surpass assume, add 5000
	if (bytesReceived > expectedBytes) {
		expectedBytes = bytesReceived + 5000 ;
	}
	
	degreeReceived = (float)bytesReceived/(float)expectedBytes ;
	if ([parentDelegate respondsToSelector:@selector(setCurrentProgress:)]) {
		NSNumber *n = [[NSNumber alloc] initWithFloat:degreeReceived];
		[parentDelegate performSelector:@selector(setCurrentProgress:) withObject:n]; 
		[n release];
	}
}

- (NSData *)dataFromData:(NSData *)data withEncoding:(NSString *)encoding
{
	NSStringEncoding nsEncoding = NSUTF8StringEncoding;
	if (encoding) {
		CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)encoding);
		if (cfEncoding != kCFStringEncodingInvalidId) {
			nsEncoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
		}
	}
	NSString *formattedString = [[[NSString alloc]initWithData:data encoding:nsEncoding]autorelease];
	NSLog(formattedString);
	return [[formattedString dataUsingEncoding:nsEncoding]retain];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection  willCacheResponse:(NSCachedURLResponse *)cachedResponse {
	// returning nil prevents the response from being cached
	return nil;
}

// Forward errors to the delegate.
- (void)connection:(NSURLConnection *)connection  didFailWithError:(NSError *)error {
	isSucess = NO;
	
	NSLog([error description]);
	
	
	if ([parentDelegate respondsToSelector:onErrorCallBack]) {
		[parentDelegate performSelector:onErrorCallBack withObject:self];
	}
	
	//UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络" message:@"网络错误，请检查" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
	//[alert show];
	
}

// Called when a chunk of data has been downloaded.
- (void)connection:(NSURLConnection *)connection {
	
}


//  the blog team's interface return differnt encoding using differnt keyword to search !!!!
//  in order NOT to crash our app, we have to enum to try all posiblility encoding that maybe used !!!
//  if we can not decoding it, we error callback
// -2147482063(GBK)   -2147482062(GB18030)  -2147481083(GB2312)  -2147481296 -2147481082(big5)
- (NSData*)getUTF8Data:(NSData*)data {
	int encode[4] = {-2147482062,-2147482063,-2147481083,-2147481296,-2147481082};
	for (int i=0; i<4; i++) {
		CFStringRef chineseStr = CFStringCreateWithBytes(NULL,[data bytes], [data length],encode[i] ,false);
		NSData *newData = [chineseStr dataUsingEncoding:NSUTF8StringEncoding];
		if (newData != nil) {
			return newData;
		}
	}
	return nil;
}

- (NSString*) getResponse{
	if (recvData) {
		NSData *newData = [self getUTF8Data:recvData];
		if (newData == nil) {
			NSLog(@"encoding error, check using right characset encoding.");
		}
		NSString* response = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
		//NSLog(@"## html:%@",response);
		return [response autorelease];
	}
	return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	NSLog(@"has recv data leng ====== %qi byte ############",bytesReceived);
	if ([parentDelegate respondsToSelector:onCompleteCallback]) {
		[parentDelegate performSelector:onCompleteCallback withObject:self];
	}
	isSucess = YES;	
}

- (BOOL) isSucess {
	return isSucess;
}

- (void)dealloc {

	[recvData release];
	recvData = nil;
	
	[connection release];
	connection =nil;
	
	[parentDelegate release];
	parentDelegate =nil;
	
	[loginCookie release];
	loginCookie = nil;
	
	NSLog(@"network end..........................................##");
	[super dealloc];
	

}


@end
